﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Security.Cryptography;
using System.Web.Security;
using TMT_CMS.BL.DB;
using TMT_CMS.BL.Model;
using TMT_CMS.BL.Model.Home;
using TMT_CMS.BL.Model.User;
using TMT_CMS.BL.Utility;

namespace TMT_CMS.BL
{
    public static class UserManager
    {
        #region RoleInfo
        public static bool CreateUserRole(string userRoleName, List<long> allPermissionIds)
        {
            TMT_VENDOR vendor = new TMT_VENDOR();
            vendor.Connection.Open();
            using (var ts = vendor.Connection.BeginTransaction())
            {
                try
                {
                    RoleInfo roleInfo = new RoleInfo() { Name = userRoleName };
                    vendor.AddToRoleInfo(roleInfo);
                    if (allPermissionIds!=null&& allPermissionIds.Count>0)
                    {
                        foreach (var permissionId in allPermissionIds)
                        {
                            Permission permission = vendor.Permission.SingleOrDefault(t => t.ID == permissionId);
                            roleInfo.Permission.Add(permission);
                        }
                    }
                    
                    vendor.SaveChanges();
                    ts.Commit();
                    return true;
                }
                catch (Exception)
                {
                    ts.Rollback();
                    return false;
                }
                finally
                {
                    vendor.Connection.Close();
                }

            }
        }

        public static RoleInfo GetRoleInfo(int roleId)
        {
            TMT_VENDOR vendor = new TMT_VENDOR();
            try
            {
                using (vendor.Connection)
                {
                    vendor.Connection.Open();
                    RoleInfo roleInfo=  vendor.RoleInfo.SingleOrDefault(t => t.ID == roleId);
                    return roleInfo;
                }
            }
            catch
            {
                return null;
            }
            finally
            {
                vendor.Connection.Close();
            }
        }

        public static PaggingResultModel<RoleInfo, UserRoleSearchModel> GetRolesInfoList(UserRoleSearchModel searchModel, PaggingRequestModel paggingModel)
        {
            TMT_VENDOR vendor = new TMT_VENDOR();
            try
            {
                using (vendor.Connection)
                {
                    vendor.Connection.Open();
                    var query = from roles in vendor.RoleInfo select roles;
                    if (!string.IsNullOrWhiteSpace(searchModel.RoleName))
                    {
                        query = query.Where(t => t.Name.IndexOf(searchModel.RoleName) > -1);
                    }

                    query = query.OrderBy(t => t.ID);

                    return DBUtility.BuildPaggingResult(query, paggingModel, searchModel);
                }
            }
            finally
            {
                vendor.Connection.Close();
            }

        }

        public static bool CheckRoleNameExists(string roleName,int id)
        {
            TMT_VENDOR vendor = new TMT_VENDOR();
            try
            {
                using (vendor.Connection)
                {
                    vendor.Connection.Open();
                    bool query = false;
                    query = id==0 ? vendor.RoleInfo.Any(t => t.Name == roleName) : vendor.RoleInfo.Any(t => t.ID != id && t.Name == roleName);
                    
                    vendor.Connection.Close();
                    return query;
                }
            }
            catch
            {
                return true;
            }
            finally
            {
                vendor.Connection.Close();
            }
        }

        /// <summary>
        /// 检测被删除的用户组下是否还存在用户
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public static bool CheckIsRoleHasUserInfo(int roleId)
        {
            TMT_VENDOR vendor = new TMT_VENDOR();
            try
            {
                using (vendor.Connection)
                {
                    vendor.Connection.Open();
                    bool query = false;
                    query = vendor.UserInfo.Any(t => t.RoleID == roleId);
                    vendor.Connection.Close();
                    return query;
                }
            }
            catch
            {
                return true;
            }
            finally
            {
                vendor.Connection.Close();
            }
        }

        public static RoleInfo  UserRoleDelete(int id)
        {
            TMT_VENDOR vendor = new TMT_VENDOR();
            try
            {
                using (vendor.Connection)
                {
                    vendor.Connection.Open();
                    RoleInfo roleInfo = vendor.RoleInfo.SingleOrDefault(t => t.ID == id);

                    return roleInfo;
                }
            }
            catch
            {
                return null;
            }
            finally
            {
                vendor.Connection.Close();
            }
        }

        public static bool DeleteRoleInfo(int id)
        {
            TMT_VENDOR vendor = new TMT_VENDOR();
            try
            {
                using (vendor.Connection)
                {
                    vendor.Connection.Open();
                    RoleInfo roleInfo = vendor.RoleInfo.SingleOrDefault(t => t.ID == id);
                    if (roleInfo!=null)
                    {
                        foreach (Permission permission in roleInfo.Permission.ToList())
                        {
                            roleInfo.Permission.Remove(permission);
                        }
                        vendor.RoleInfo.DeleteObject(roleInfo);
                        vendor.SaveChanges();
                    }
                    return true;
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                vendor.Connection.Close();
            }
        }


        public static bool UserRoleUpdate(UserRoleEditModel roleView)
        {
            TMT_VENDOR vendor = new TMT_VENDOR();
            try
            {
                using (vendor.Connection)
                {
                    vendor.Connection.Open();
                    RoleInfo roleInfo = vendor.RoleInfo.SingleOrDefault(t => t.ID == roleView.ID);
                    
                    if (roleInfo != null)
                    {
                        roleInfo.Name = roleView.RoleName;
                        roleInfo.Permission.Clear();
                        if (roleView.PermissionIDs!=null)
                        {
                            foreach (long permissionID in roleView.PermissionIDs)
                            {
                                roleInfo.Permission.Add(vendor.Permission.SingleOrDefault(t => t.ID == permissionID));
                            }
                        }
                       
                        vendor.SaveChanges();

                    }
                    return true;
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                vendor.Connection.Close();
            }
        }

        public static  List<RoleInfo> GetRoleInfoList()
        {
            TMT_VENDOR vendor = new TMT_VENDOR();
            vendor.Connection.Open();
            using (vendor.Connection)
            {
                var query = from role in vendor.RoleInfo select role;
                return query.ToList();
            }
        }

       
        #endregion

        #region User
        public static PaggingResultModel<UserInfo, UserSearchModel> GetUserList(UserSearchModel searchModel, PaggingRequestModel paggingModel)
        {
            TMT_VENDOR db = new TMT_VENDOR();
            try
            {
                db.Connection.Open();

                // build query
                var query = (from user in db.UserInfo select user);
                if (!string.IsNullOrWhiteSpace(searchModel.Username))
                {
                    query = query.Where(q => q.Username == searchModel.Username);
                }

                if (!string.IsNullOrWhiteSpace(searchModel.FamilyName))
                {
                    query = query.Where(q => q.FamilyName.StartsWith(searchModel.FamilyName));
                }
                query = query.OrderBy(q => q.ID);

                return DBUtility.BuildPaggingResult<UserInfo, UserSearchModel>(query, paggingModel, searchModel);
            }
            finally
            {
                db.Connection.Close();
            }
        }

        public static List<PermissionEx> GetPrermissionList(int roleId)
        {
            TMT_VENDOR vendor = new TMT_VENDOR();
            using (vendor.Connection)
            {
                vendor.Connection.Open();
                var query = from permission in vendor.Permission
                            select new PermissionEx()
                            {
                                ID = permission.ID,
                                Name = permission.Name,
                                IsChecked = vendor.RoleInfo.Any(t => t.Permission.Contains(permission) && t.ID == roleId)
                            };
                return query.ToList();
            }
        }

        public static void CreateUser(UserInfoViewModel userInfo)
        {
            TMT_VENDOR vendor = new TMT_VENDOR();
            vendor.Connection.Open();
            using (vendor.Connection)
            {
                UserInfo user = new UserInfo()
                    {
                        CreateTime = DateTime.Now,
                        Email = userInfo.Email,
                        FamilyName = userInfo.FamilyName,
                        Password = FormsAuthentication.HashPasswordForStoringInConfigFile(userInfo.Password, "MD5"),
                        RoleInfo =  vendor.RoleInfo.SingleOrDefault(t => t.ID == userInfo.RoleIDs),
                        Username = userInfo.UserName,
                        Status = 1
                    };
                vendor.AddToUserInfo(user);
                vendor.SaveChanges();
            }
        }

        public static void UpdateUser(UserInfoEditModel editModel)
        {
            TMT_VENDOR vendor = new TMT_VENDOR();
            vendor.Connection.Open();
            using (vendor.Connection)
            {
                UserInfo user = vendor.UserInfo.SingleOrDefault(t => t.ID == editModel.ID);
                if (user != null)
                {
                    user.Email = editModel.Email;
                    user.FamilyName = editModel.FamilyName;
                    if (!string.IsNullOrWhiteSpace(editModel.Password))
                    {
                        user.Password = FormsAuthentication.HashPasswordForStoringInConfigFile(editModel.Password, "MD5");
                    }
                    user.RoleInfo = vendor.RoleInfo.SingleOrDefault(t => t.ID == editModel.RoleIDs);
                    user.Username = editModel.UserName;
                    vendor.SaveChanges();
                }
            }
        }

        public static bool CheckUserNameIsExist(int id,string userName)
        {
            TMT_VENDOR vendor = new TMT_VENDOR();
            try
            {
                using (vendor.Connection)
                {
                    vendor.Connection.Open();
                    bool query = false;
                    query = id == 0
                                ? vendor.UserInfo.Any(t => t.Username == userName)
                                : vendor.UserInfo.Any(t => t.ID != id && t.Username == userName);

                    vendor.Connection.Close();
                    return query;
                }
            }
            catch
            {
                return true;
            }
            finally
            {
                vendor.Connection.Close();
            }
        }

        public static UserInfo GetUserInfo(int userId)
        {
            TMT_VENDOR vendor = new TMT_VENDOR();
            try
            {
                using (vendor.Connection)
                {
                    vendor.Connection.Open();
                    var query = vendor.UserInfo.SingleOrDefault(t => t.ID == userId);
                    vendor.Connection.Close();
                    return query;
                }
            }
            finally
            {
                vendor.Connection.Close();
            }
        }

        public static  void DeleteUserInfo(int userId)
        {
            TMT_VENDOR vendor = new TMT_VENDOR();
            try
            {
                using (vendor.Connection)
                {
                    vendor.Connection.Open();
                    var query = vendor.UserInfo.SingleOrDefault(t => t.ID == userId);
                    vendor.DeleteObject(query);
                    vendor.SaveChanges();
                }
            }
            finally
            {
                vendor.Connection.Close();
            }
        }


        public static UserInfo UserLogin(UserLoginModel userLoginModel)
        {
            TMT_VENDOR vendor = new TMT_VENDOR();
            try
            {
                using (vendor.Connection)
                {
                    string md5 = FormsAuthentication.HashPasswordForStoringInConfigFile(userLoginModel.Password, "MD5");
                    vendor.Connection.Open();

                    UserInfo user = vendor.UserInfo.SingleOrDefault(
                        u =>
                        u.Username.ToUpper() == userLoginModel.UserName.Trim().ToUpper() &&
                        u.Password.Trim().ToUpper() ==md5.ToUpper()
                        );
                    if (user==null)
                    {
                        return null;
                    }
                    else
                    {
                        FormsAuthentication.RedirectFromLoginPage(user.Username, false);
                        return user;
                    }
                }
            }
            finally
            {
                vendor.Connection.Close();
            }
        }
        #endregion
    }
}
